<script setup lang="ts">
import { onMounted, reactive } from 'vue';
import { getCurrentInstance, navigateTo, showLoading } from '@tarojs/taro';
import { QUERY_APP_WO_DELIVER_DETAIL, END_APP_TASK } from '/@/api/modules/deliver/app-wo-deliver';
import { ACCESS } from '/@/api/modules/qrcode/open';
import { SYS_REGION_LIST } from '/@/api/modules/base/sys-region';
import { scan } from '/@/utils/scan';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  id: string;
};

const state = reactive<{
  /**
   * 工单信息
   */
  info: AppWoDeliver.Dto;
}>({
  info: {},
});

const formState = reactive<{
  woDeliverEventDto: AppWoDeliver.eventDto;
  woDeliverDto: AppWoDeliver.Dto;
}>({
  woDeliverEventDto: {
    workOrderId: '',
    handleUserId: '',
    handleUserName: '',
    handleTime: undefined,
    opinion: '',
    woDeliverEventFileDto: [],
  },
  woDeliverDto: {
    id: '',
  },
});

/**
 * @function 上传文件
 * @param imgList
 */
function uploadImageChange(imgList: { key: string; src: string }[]) {
  formState.woDeliverEventDto.woDeliverEventFileDto = imgList.map((i) => {
    return {
      fileType: 1,
      fileUrl: i.src,
      fileName: i.src.split('/').reverse()[0],
    };
  }) as AppWoDeliver.eventFileDto[];
}

function submit() {
  endAppTaskScan();
}

/**
 * 结束运送工单-扫描
 */
function endAppTaskScan() {
  scan().then((res) => {
    scanResult(res);
  });
}

/**
 * 结束运送工单
 */
function endAppTask(areaId?: string, areaName?: string) {
  formState.woDeliverDto.id = params.id;
  formState.woDeliverEventDto.workOrderId = params.id;
  formState.woDeliverEventDto.qrcodeAreaId = areaId;
  formState.woDeliverEventDto.qrcodeAreaName = areaName;
  showLoading();
  END_APP_TASK(formState).then(() => {
    formState.woDeliverEventDto = {
      workOrderId: '',
      handleUserId: '',
      handleUserName: '',
      handleTime: undefined,
      opinion: '',
      woDeliverEventFileDto: [],
    };
    formState.woDeliverDto = {
      id: '',
    };
    navigateTo({
      url: `/pages/deliver/scan-success/index?status=task_end&id=${params.id}`,
    });
  });
}

/**
 * 扫描结果处理
 */
function scanResult(result: string) {
  const url = new URL(result);
  const t = url.searchParams.get('t');
  if (!t) {
    navigateTo({
      url: `/pages/deliver/scan-fail/index?status=task_end&id=${params.id}`,
    });
    return;
  }
  ACCESS({ t: t }).then((res) => {
    if (res.comResp?.code !== 100) {
      navigateTo({
        url: `/pages/deliver/scan-fail/index?status=task_end&id=${params.id}`,
      });
      return;
    }
    /**
     * 获取参数信息
     */
    const contentParams = res.content?.params as {
      id: string;
    };
    switch (res.content?.businessTag) {
      case 'AREA_DETAIL':
        queryAreaDetail(contentParams.id);
        break;
    }
  });
}

//根据id查询详情信息
function queryAreaDetail(areaId: string, page: number = 1, pageSize: number = 15) {
  showLoading();
  SYS_REGION_LIST({
    comQuery: { page, pageSize },
    id: areaId,
  }).then((res) => {
    if (!res.content || !res.content.length) return;
    //扫描的区域ID和工单开始地址ID相等
    const areaId = res.content[0].id;
    const areaName = res.content[0].name;
    if (state.info.areaIdEnd === areaId) {
      endAppTask(areaId, areaName);
    } else {
      navigateTo({
        url: `/pages/deliver/scan-fail/index?status=task_end&id=${params.id}`,
      });
    }
  });
}

/**
 * @function 获取工单详情
 */
function getDetail() {
  showLoading();
  QUERY_APP_WO_DELIVER_DETAIL({ id: params.id }).then((res) => {
    state.info = res.woDeliverDto;
  });
}

onMounted(() => {
  getDetail();
});
</script>

<template>
  <view class="deliver-process app-page--1">
    <app-navbar title="处理" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="deliver-process__wrapper">
        <nut-form :model-value="formState" class="deliver-process__form">
          <nut-form-item class="nut-form__title-wrapper" label="处理说明" />
          <nut-form-item>
            <nut-textarea
              v-model="formState.woDeliverEventDto.opinion"
              placeholder="请输入处理说明"
              rows="8"
              limit-show
              text-align="left"
              max-length="200"
            />
          </nut-form-item>
          <nut-form-item label="上传图片" />
          <nut-form-item label-width="0">
            <app-upload-image @on-change="uploadImageChange" height="120px" :max="3" />
          </nut-form-item>
        </nut-form>
      </view>
    </scroll-view>
    <view class="deliver-process__footer">
      <nut-button block type="info" @click="submit">
        <text>扫码提交</text>
      </nut-button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
